package cn.wangsy.contacts;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {

	public static void main(String[] args){
		Client client = new Client();
		client.init();
	}
	
	public void init(){
		Socket socket = null;
		Scanner scanner = new Scanner(System.in);
		boolean flag = true;
		
		while(flag){
			String cmd = scanner.nextLine();
			if(cmd.startsWith("CONNECT")){
				String cmds[] = cmd.split(" ");
				if(cmds.length == 3){
					try {
						socket = new Socket(cmds[1], Integer.parseInt(cmds[2]));
						if(!isServerClose(socket)){
							System.out.println("连接成功");
							flag = false;
							handle(socket,scanner);
						}
					} catch (Exception exception) {
						System.out.println("连接失败");
					}
				}else{
					System.out.println("CONNECT 参数错误");
				}
			}else if(cmd.startsWith("BYE")){
				break;
			}else{
				System.out.println("Error command");
			}
		}
	}

	public void handle(Socket socket,Scanner scanner){
		
		PrintWriter writer = null ;
		BufferedReader reader = null ;
		try {
			writer = new PrintWriter(socket.getOutputStream());
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		while (true) {
			String cmd = scanner.nextLine();
			try {
				writer.println(cmd);
				writer.flush();
				System.out.println(reader.readLine());
				if(cmd.startsWith("BYE")){
					writer.close();
					reader.close();
					break;
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		scanner.close();
	}
	
	public boolean isServerClose(Socket socket){ 
	   try{ 
		   socket.sendUrgentData(0xFF);//发送1个字节的紧急数据，默认情况下，服务器端没有开启紧急数据处理，不影响正常通信 
		   return false; 
	   }catch(Exception se){ 
		   return true; 
	   } 
	} 
	
}
